﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;

public class GetRawDataEdt
{
    [MenuItem("资源工具/提取RawData")]
    public static void CreateIcon()
    {
        string path = "Assets/Res";
        GetIcon(path);
    }

    static void GetIcon(string rootPath)
    {
        string[] files = Directory.GetFiles(rootPath, "*.*", SearchOption.AllDirectories);

        int cnt = files.Length;
        for (int i = 0; i < cnt; i++)
        {
            string filePath = files[i];
            if (filePath.EndsWith(".meta"))
                continue;

            float per = (float)(i + 1) / (float)cnt;
            EditorUtility.DisplayCancelableProgressBar("正在提取", filePath, per);

            AssetImporter assImp = AssetImporter.GetAtPath(filePath);
            OnPostprocessGetIcon(assImp);
        }

        EditorUtility.ClearProgressBar();
    }

    public static void OnPostprocessGetIcon(AssetImporter tmp)
    {
        TextureImporter texImp = tmp as TextureImporter;
        if (texImp == null)
            return;

        Texture2D tex = AssetDatabase.LoadAssetAtPath<Texture2D>(texImp.assetPath);

        byte[] rawData = tex.GetRawTextureData();

        string newPath = texImp.assetPath.Replace("Res/", "ResPickUp/");
        string dirPath = System.IO.Path.GetDirectoryName(newPath);

        if (!Directory.Exists(dirPath))
            Directory.CreateDirectory(dirPath);

        MemoryStream stream = new MemoryStream(rawData.Length + 64);
        byte[] wb = System.BitConverter.GetBytes(tex.width);
        byte[] hb = System.BitConverter.GetBytes(tex.height);

        stream.Write(wb, 0, wb.Length);
        stream.Write(hb, 0, hb.Length);
        stream.Write(rawData, 0, rawData.Length);

        string exName = Path.GetExtension(newPath);
        newPath = newPath.Replace(exName, ".bytes");

        File.WriteAllBytes(newPath, stream.GetBuffer());
    }
}
